package main

import (
    "context"
    "fmt"
	"encoding/csv"    
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "time"
)

func monitorAndTrigger(client *mongo.Client, timeWindows []time.Duration, writer *csv.Writer) {
    triggered := make(map[float64]bool)
    // timeWindows := []time.Duration{10 * time.Second, 1 * time.Hour}

    for {
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        var result bson.M
        err := client.Database(databaseName).RunCommand(ctx, bson.D{{"dbStats", 1}}).Decode(&result)
        cancel()
        if err != nil {
            fmt.Printf("[Monitor] 获取数据库大小失败: %v\n", err)
            time.Sleep(5 * time.Second)
            continue
        }

        sizeBytes := result["dataSize"].(float64)
        sizeGB := sizeBytes / 1024 / 1024 / 1024
        fmt.Printf("[Monitor] 当前数据库大小: %.2f GB\n", sizeGB)

        for _, th := range thresholds {
            if sizeGB >= th && !triggered[th] {
                fmt.Printf(">>> 触发阈值 %.2fGB，开始查询...\n", th)
                for _, window := range timeWindows {
                    runQueryTests(client, window, writer, th)
                }
                triggered[th] = true
            }
        }

        // 如果所有阈值都被触发，结束
        allTriggered := true
        for _, th := range thresholds {
            if !triggered[th] {
                allTriggered = false
                break
            }
        }
        if allTriggered {
            fmt.Println("所有阈值已完成查询，程序结束。")
            return
        }

        time.Sleep(10 * time.Second)
    }
}
